package cn.zwk.entity;

import lombok.Data;

import java.util.List;

@Data
public class MultiRowItem extends AbstractItem {
    private String label;
    private List<DataRow> rows;
    private double sum;
    private double count;
    
    // 添加便捷方法来设置双向关联
    public void setRows(List<DataRow> rows) {
        this.rows = rows;
        if (rows != null) {
            for (DataRow row : rows) {
                row.setParent(this);
            }
        }
    }
    
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        if (rows != null) {
            for (DataRow row : rows) {
                sb.append(row.toString()).append("\n");
            }
        }
        String name = getParent().getName();
        long timestamp = getTimestamp();
        String sumKey = addHostTag(name + "_sum" + (label != null ? label : ""));
        String countKey = addHostTag(name + "_count" + (label != null ? label : ""));
        sb.append(String.format("%s %.6f %d\n", sumKey, sum, timestamp));
        sb.append(String.format("%s %.0f %d\n", countKey, count, timestamp));
        return sb.toString();
    }
    
    private long getTimestamp() {
        if (getParent() != null && getParent().getParent() != null) {
            return getParent().getParent().getTimestamp();
        }
        return System.currentTimeMillis();
    }
    
    private String addHostTag(String originalKey) {
        if (getParent() != null && getParent().getParent() != null) {
            String hostName = getParent().getParent().getHostName();
            if (hostName != null && !hostName.isEmpty()) {
                if (originalKey.contains("{") && originalKey.contains("}")) {
                    // 已经有标签，在现有标签内部添加tag
                    int openBraceIndex = originalKey.indexOf("{");
                    int closeBraceIndex = originalKey.lastIndexOf("}");
                    String beforeBrace = originalKey.substring(0, openBraceIndex + 1);
                    String existingLabels = originalKey.substring(openBraceIndex + 1, closeBraceIndex);
                    String afterBrace = originalKey.substring(closeBraceIndex);
                    
                    // 如果现有标签不为空，则在前面加逗号
                    String tagToAdd = existingLabels.isEmpty() ? 
                        "tag=\"" + hostName + "\"" : 
                        "tag=\"" + hostName + "\"," + existingLabels;
                    
                    return beforeBrace + tagToAdd + afterBrace;
                } else {
                    // 没有标签，添加新标签
                    return originalKey + "{tag=\"" + hostName + "\"}";
                }
            }
        }
        return originalKey;
    }
}
